const moment = require('moment');
let userDao = require('../dao/userDao');
let logger = require('pomelo-logger').getLogger("createagain");
let pushAPI = require('../API/pushAPI');

class createRoomAgain {


    static getInstance() {
        if (!createRoomAgain.instance) {
            createRoomAgain.instance = new createRoomAgain();
        }
        return createRoomAgain.instance;
    }

    constructor() {

        this.createRoomTimer = {};
        this.createUserList = {};
        this.createRoomIntervalID = {};
        this.curJoinUser = {};

    }

    //新增玩家排队
    async addUserList(roomID, userInfo, union, gameRuleID, gameRule) {


        logger.info(`[createRoomAgain] uid = ${userInfo.uid} game Again roomID = ${roomID} gameRuleID = ${gameRuleID} `);
        if (!this.createUserList[roomID]) {

            let createTime = moment().format('x');
            let endTime = moment().add(10, 's').format('x');
            let isCreated = false;
            let creatrUser = null;
            let joinUserList = [];
            let joinRoomID = null;
            let pendingUserList = [];
            let isJoined = true;
            this.createUserList[roomID] = { isJoined, joinRoomID, createTime, endTime, union, gameRuleID, gameRule, isCreated, creatrUser, joinUserList, pendingUserList };
            this.createRoomIntervalID[roomID] = setInterval(() => {
                if (!this.curJoinUser[roomID]) {
                    this.addUserToGame(roomID);
                }
            }, 200);
        }
        //判断是否加入过了
        if (!this.createUserList[roomID].pendingUserList.find(item => item.uid == userInfo.uid) && !this.createUserList[roomID].joinUserList.includes(userInfo.uid)) {
            this.createUserList[roomID].pendingUserList.push(userInfo);
        }
    }


    async addUserToGame(roomID) {


        //  logger.info(`[createRoomAgain] addUserToGame begin roomID = ${roomID}`);
        let curCreateRoomInfo = this.createUserList[roomID];
        if (!curCreateRoomInfo) return;

        //结束 删除定时器及对象
        if (curCreateRoomInfo && moment().format('x') > curCreateRoomInfo.endTime) {
            this.clearRoomData(roomID);
        }

        let union = curCreateRoomInfo.union;
        //如果当前操作执行完毕
        if (curCreateRoomInfo && union && curCreateRoomInfo.isJoined) {
            let userInfo = curCreateRoomInfo.pendingUserList.shift();
            if (userInfo && !curCreateRoomInfo.joinUserList.includes(userInfo.uid)) {
                this.curJoinUser[roomID] = userInfo;
                this.createUserList[roomID].isJoined = false;
                if (curCreateRoomInfo.joinRoomID) {
                    //走加入房间
                    let resCode = await union.joinRoom(curCreateRoomInfo.joinRoomID, userInfo);
                    if (resCode == 0) {
                        this.createUserList[roomID].joinUserList.push(userInfo.uid);
                        logger.info(`[createRoomAgain] uid = ${userInfo.uid} join roomID = ${curCreateRoomInfo.joinRoomID} success userList = ${this.createUserList[roomID].joinUserList}`);
                    }
                    else {
                        pushAPI.joinGameAgainPush({ uid: userInfo.uid, code: resCode }, [{ uid: userInfo.uid, sid: userInfo.frontendId }]);
                        logger.error(`[createRoomAgain] uid = ${userInfo.uid} join roomID = ${curCreateRoomInfo.joinRoomID} fail code = ${resCode} `);
                    }
                    this.createUserList[roomID].isJoined = true;
                    this.curJoinUser[roomID] = null;
                } else {
                    //创建房间
                    let resCode = await union.createRoom(curCreateRoomInfo.gameRuleID, curCreateRoomInfo.gameRule, userInfo);
                    if (resCode == 0) {
                        //获取当前玩家的房间ID
                        let newUserData = await userDao.getUserDataByUid(userInfo.uid);
                        this.createUserList[roomID].joinRoomID = newUserData.roomID;
                        this.createUserList[roomID].joinUserList.push(userInfo.uid);
                        logger.info(`[createRoomAgain] uid = ${userInfo.uid} oldRoomID = ${roomID} create roomID = ${curCreateRoomInfo.joinRoomID} success userList = ${this.createUserList[roomID].joinUserList}`);
                    } else {
                        logger.info(`[createRoomAgain] uid = ${userInfo.uid} create fail code = ${resCode}`);
                        pushAPI.joinGameAgainPush({ uid: userInfo.uid, code: resCode }, [{ uid: userInfo.uid, sid: userInfo.frontendId }]);
                    }
                    this.createUserList[roomID].isJoined = true;
                    this.curJoinUser[roomID] = null;
                }
            }
        }
    }

    clearRoomData(roomID) {

        logger.info(`[createRoomAgain] clear join again data roomID = ${roomID}`);
        if (this.createRoomIntervalID[roomID]) {
            clearInterval(this.createRoomIntervalID[roomID]);
            delete this.createRoomIntervalID[roomID];
            this.createRoomIntervalID[roomID] = null;
        }
        delete this.createUserList[roomID];
        delete this.curJoinUser[roomID];
    }

}

module.exports = createRoomAgain;